package com.heatup.apt.common.util.Netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

/**
 * Created by blank on 2017/11/17 上午10:43
 */
public class HttpsCodecInitializer extends ChannelInitializer<Channel> {

    private final SSLContext context;
    private final boolean client;

    public HttpsCodecInitializer(SSLContext context, boolean client) {
        this.context = context;
        this.client = client;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {

        ChannelPipeline pipeline = ch.pipeline();
//        SSLEngine engine = context.newEngine(ch.alloc());
        SSLEngine engine = context.createSSLEngine();
        pipeline.addFirst("ssl", new SslHandler(engine)); //添加 SslHandler 到 pipeline 来启用 HTTPS

        if (client) {
            pipeline.addLast("codec", new HttpClientCodec()); //client: 添加 HttpClientCodec
        } else {
            pipeline.addLast("codec", new HttpServerCodec()); //server: 添加 HttpServerCodec ，如果是 server 模式的话
        }

    }
}
